import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Skeleton, List, Typography, Tag, Divider } from 'antd';
import { UserOutlined, RobotOutlined, ApiOutlined, MessageOutlined } from '@ant-design/icons';
import { 
  getSystemResources, 
  SystemResourcesDto, 
  getDashboardStats, 
  MonitorStatsDto,
  getActivityLogs,
  ActivityLogDto
} from '@/apis/backhub/monitor';

const { Text } = Typography;

// 文本截断样式 - 允许多行，超出部分显示省略号
const ellipsisTextStyle = {
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  display: '-webkit-box' as const,
  WebkitLineClamp: 2,
  WebkitBoxOrient: 'vertical' as const,
  wordBreak: 'break-word' as const,
  whiteSpace: 'normal' as const
};

// 活动时间文本样式
const activityTimeStyle = {
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  whiteSpace: 'nowrap' as const,
  maxWidth: '100%'
};

// 活动列表样式
const activityListStyle = {
  width: '100%',
  height: '100%'
};

// 系统状态样式
const systemStatusStyle = {
  lineHeight: '2',
  padding: '8px 0'
};

// 列表样式
const listStyle = {
  width: '100%',
  height: '100%'
};

// 卡片样式
const cardStyle = {
  display: 'flex',
  flexDirection: 'column' as const,
  height: '100%'
};

// 卡片内容样式
const cardBodyStyle = {
  flex: 1,
  height: '100%',
  overflow: 'auto'
};

// 行样式
const rowStyle = {
  marginTop: '24px', 
  display: 'flex',
  alignItems: 'stretch'
};

// 处理请求内容的函数，添加双引号并移除HTML标签
const formatRequestContent = (content: string | undefined): string => {
  if (!content) return "";
  // 移除HTML标签
  const textContent = content.replace(/<\/?[^>]+(>|$)/g, '');
  return `${textContent}`; 
};

// 统计数字颜色
const statisticColors = {
  users: '#1890ff',      // 蓝色
  agents: '#52c41a',     // 绿色
  apiCalls: '#722ed1',   // 紫色
  conversations: '#fa8c16' // 橙色
};

// 系统状态颜色函数
const getCpuColor = (usage: number) => {
  if (usage < 50) return '#52c41a'; // 绿色 - 低负载
  if (usage < 80) return '#faad14'; // 黄色 - 中等负载
  return '#f5222d'; // 红色 - 高负载
};

const getMemoryColor = (usage: number) => {
  if (usage < 60) return '#52c41a'; // 绿色 - 低使用率
  if (usage < 85) return '#faad14'; // 黄色 - 中等使用率
  return '#f5222d'; // 红色 - 高使用率
};

const getStorageColor = (usage: number, total: number) => {
  const percentage = (usage / total) * 100;
  if (percentage < 70) return '#52c41a'; // 绿色 - 足够空间
  if (percentage < 90) return '#faad14'; // 黄色 - 注意空间
  return '#f5222d'; // 红色 - 空间不足
};

const Dashboard: React.FC = () => {
  const [systemLoading, setSystemLoading] = useState<boolean>(true);
  const [dashboardLoading, setDashboardLoading] = useState<boolean>(true);
  const [activityLoading, setActivityLoading] = useState<boolean>(true);
  const [systemResources, setSystemResources] = useState<SystemResourcesDto>({
    cpuUsage: 0,
    memoryUsage: 0,
    usedStorage: 0,
    totalStorage: 0,
    uptimeMinutes: 0,
    formattedUptime: ''
  });
  const [dashboardStats, setDashboardStats] = useState<MonitorStatsDto>({
    totalUsers: 0,
    totalAgents: 0,
    totalApiCalls: 0,
    totalConversations: 0
  });
  const [activityLogs, setActivityLogs] = useState<ActivityLogDto[]>([]);

  // 初始化时加载数据
  useEffect(() => {
    fetchSystemResources();
    fetchDashboardStats();
    fetchActivityLogs();
  }, []);

  // 获取系统资源数据
  const fetchSystemResources = async () => {
    setSystemLoading(true);
    try {
      const data = await getSystemResources();
      setSystemResources(data);
    } catch (error) {
      console.error('获取系统资源数据失败:', error);
    } finally {
      setSystemLoading(false);
    }
  };

  // 获取仪表盘统计数据
  const fetchDashboardStats = async () => {
    setDashboardLoading(true);
    try {
      const data = await getDashboardStats();
      setDashboardStats(data);
    } catch (error) {
      console.error('获取仪表盘统计数据失败:', error);
    } finally {
      setDashboardLoading(false);
    }
  };

  // 获取活动日志数据
  const fetchActivityLogs = async () => {
    setActivityLoading(true);
    try {
      const data = await getActivityLogs(4); // 只获取4条记录
      setActivityLogs(data);
    } catch (error) {
      console.error('获取活动日志数据失败:', error);
    } finally {
      setActivityLoading(false);
    }
  };

  // 格式化运行时间，去掉秒数
  const formatUptime = (uptime: string) => {
    // 移除秒数部分
    return uptime.replace(/\d+秒$/, '');
  };

  // 统计卡片渲染
  const renderStatisticCard = (title: string, value: number | undefined, prefix: React.ReactNode, color: string) => {
    return (
      <Card>
        {dashboardLoading ? (
          <Skeleton active paragraph={{ rows: 1 }} title={{ width: '50%' }} />
        ) : (
          <Statistic
            title={title}
            value={value || 0}
            prefix={prefix}
            valueStyle={{ color: color }}
          />
        )}
      </Card>
    );
  };

  return (
    <div>
      <h2>控制台</h2>
      
      <Row gutter={[16, 16]}>
        <Col span={6}>
          {renderStatisticCard("总用户数", dashboardStats.totalUsers, <UserOutlined />, statisticColors.users)}
        </Col>
        
        <Col span={6}>
          {renderStatisticCard("智能体数量", dashboardStats.totalAgents, <RobotOutlined />, statisticColors.agents)}
        </Col>
        
        <Col span={6}>
          {renderStatisticCard("API调用次数", dashboardStats.totalApiCalls, <ApiOutlined />, statisticColors.apiCalls)}
        </Col>
        
        <Col span={6}>
          {renderStatisticCard("对话总数", dashboardStats.totalConversations, <MessageOutlined />, statisticColors.conversations)}
        </Col>
      </Row>
      
      <Row gutter={[16, 16]} style={rowStyle}>
        <Col span={12}>
          <Card title="系统状态" style={cardStyle} bodyStyle={cardBodyStyle}>
            {systemLoading ? (
              <Skeleton active paragraph={{ rows: 4 }} title={false} />
            ) : (
              <div style={systemStatusStyle}>
                <p>
                  <Text strong>CPU使用率: </Text>
                  <Text style={{ color: getCpuColor(systemResources.cpuUsage) }}>
                    {systemResources.cpuUsage.toFixed(2)}%
                  </Text>
                </p>
                <p>
                  <Text strong>内存使用率: </Text>
                  <Text style={{ color: getMemoryColor(systemResources.memoryUsage) }}>
                    {systemResources.memoryUsage.toFixed(2)}%
                  </Text>
                </p>
                <p>
                  <Text strong>存储空间: </Text>
                  <Text style={{ color: getStorageColor(systemResources.usedStorage, systemResources.totalStorage) }}>
                    {systemResources.usedStorage.toFixed(2)}GB/{systemResources.totalStorage.toFixed(2)}GB
                  </Text>
                </p>
                <p>
                  <Text strong>运行时间: </Text>
                  <Text style={{ color: '#1890ff' }}>
                    {formatUptime(systemResources.formattedUptime)}
                  </Text>
                </p>
                <Divider style={{ margin: '12px 0' }} />
                <div style={{ fontSize: '12px', color: '#666' }}>
                  <p style={{ marginBottom: '8px' }}><Text strong>状态说明：</Text></p>
                  <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                    <Tag color="#52c41a">正常</Tag>
                    <Tag color="#faad14">注意</Tag>
                    <Tag color="#f5222d">警告</Tag>
                  </div>
                  <p style={{ marginTop: '8px', fontSize: '12px' }}>
                    CPU: <Text type="secondary">正常(&lt;50%) 注意(50-80%) 警告(&gt;80%)</Text><br />
                    内存: <Text type="secondary">正常(&lt;60%) 注意(60-85%) 警告(&gt;85%)</Text><br />
                    存储: <Text type="secondary">正常(&lt;70%) 注意(70-90%) 警告(&gt;90%)</Text>
                  </p>
                </div>
              </div>
            )}
          </Card>
        </Col>
        
        <Col span={12}>
          <Card title="最近活动" style={cardStyle} bodyStyle={cardBodyStyle}>
            {activityLoading ? (
              <Skeleton active paragraph={{ rows: 4 }} title={false} />
            ) : (
              <List
                itemLayout="horizontal"
                style={listStyle}
                dataSource={activityLogs}
                renderItem={(item) => (
                  <List.Item style={{ padding: '8px 0', borderBottom: '1px solid #f0f0f0' }}>
                    <List.Item.Meta
                      title={
                        <div style={ellipsisTextStyle}>
                          {item.username ? (
                            <div>
                              <Text style={{ marginRight: '4px' }}>用户</Text>
                              <Text type="secondary" style={{ marginRight: '4px' }}>'{item.username}'</Text>
                              <Text style={{ marginRight: '4px' }}>发起请求，请求内容为：</Text>
                              <br />
                              <Text type="secondary" style={{ display: 'block', marginTop: '4px', paddingLeft: '8px', borderLeft: '2px solid #f0f0f0' }}>
                                {formatRequestContent(item.requestContent)}
                              </Text>
                            </div>
                          ) : (
                            <Text type="secondary">{formatRequestContent(item.requestContent)}</Text>
                          )}
                        </div>
                      }
                      description={
                        <Text type="secondary" style={activityTimeStyle}>{item.timeAgo}</Text>
                      }
                    />
                  </List.Item>
                )}
              />
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard; 